package control;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.Integer;

import dataaccess.UsersDB;
import domain.CarList;
import domain.ItemOrder;
import domain.ShoppingCart;
import domain.User;

public class ShoppingCartAction extends HttpServlet {
	boolean followForward = true;// flag used to make sure the page only
	// forwards the request once
	UsersDB udb = new UsersDB();// connects to the users database

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();

		User user = (User) session.getAttribute("userinfo");
		if (user == null || !udb.checkLogin(user)) {
			// we perform the login check just in case the user came here
			// without having passed through the login servlet
			if (followForward) {
				System.out
						.println("user info not found or incorrect -- redirecting to login page ");

				getServletConfig().getServletContext()
						.getRequestDispatcher("/LoginPage.jsp")
						.forward(request, response);
				followForward = false;
			}
			
		} else {
			if (session.getAttribute("shoppingcart") == null) {
				// if there is no shopping cart we create a new one.
				// this happens when this servlet is accessed for the first time
				session.setAttribute("shoppingcart", new ShoppingCart());
			}
			int quantity=0;
			String itemid="";
			if(request.getParameter("itemid")!=null){
			System.out.println("itemid parameter value is: "+request.getParameter("itemid"));
			itemid=request.getParameter("itemid");}
			if(request.getParameter("quantity")!=null){
			System.out.println("quantity parameter value is: "+request.getParameter("quantity"));
			quantity=Integer.parseInt(request.getParameter("quantity"));}
			ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingcart");
			//CarList list =(CarList)session.getAttribute("carlist");
			ItemOrder order = new ItemOrder( );
			order.setItemID(itemid);
			order.setQuantity(quantity);
			cart.addItem(order);
			session.setAttribute("shoppingcart", cart);
			getServletConfig().getServletContext()
			.getRequestDispatcher("/ShoppingCartPage.jsp")
			.forward(request, response);
			
			
			
		}

	}// end doPost
}
